package com.cs.framework.web.view;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;

import com.cs.framework.core.context.Application;
import com.cs.framework.web.view.support.ForwardView;
import com.cs.framework.web.view.support.JsonView;
import com.cs.framework.web.view.support.ReDirectView;

/**
 * 视图工厂
 * 
 * @author hedongzhou
 * 
 */
public class ViewFactory {

	/**
	 * 存放视图
	 */
	protected Map<String, View> viewMap = new HashMap<String, View>();

	public ViewFactory(Application application) {
		initDefaultView();

		initCustomView(application);

		for (View view : viewMap.values()) {
			view.init(application);
		}
	}

	/**
	 * 初始化默认的视图
	 * 
	 * @param application
	 */
	protected void initDefaultView() {
		viewMap.put(DefaultViewName.JSON_VIEW, new JsonView());
		viewMap.put(DefaultViewName.REDIRECT_VIEW, new ReDirectView());
		viewMap.put(DefaultViewName.FORWARD_VIEW, new ForwardView());
	}

	/**
	 * 初始化自定义的视图
	 * 
	 * @param application
	 */
	protected void initCustomView(Application application) {
		// 获取自定义的视图
		Map<String, View> tempMap = BeanFactoryUtils.beansOfTypeIncludingAncestors((ApplicationContext) application,
				View.class);
		if (!tempMap.isEmpty()) {
			// 如果自定义的视图名称与默认的视图一样，则覆盖后者
			viewMap.putAll(tempMap);
		}
	}

	/**
	 * 获取视图
	 * 
	 * @param viewName
	 *            视图名称，若为空，则默认JSON视图
	 * @return
	 */
	public View getView(String viewName) {
		return viewMap.get(viewName);
	}

}
